import os
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.config import db

origins = ["http://localhost:3000"]


def init_app():
    db.init()

    app = FastAPI(title="App", version="1")

    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    @app.on_event("startup")
    async def starup():
        await db.create_all()

    @app.on_event("shutdown")
    async def shutdown():
        await db.close()

    from app.controller import authentication, users, data, token, school

    app.include_router(authentication.router)
    app.include_router(users.router)
    app.include_router(data.router)
    app.include_router(token.router)
    app.include_router(school.router)

    return app


app = init_app()


def start():
    """Launched with 'poetry run start' at root level"""
    uvicorn.run("main:app", host="localhost", port=8888, reload=True)


if __name__ == "__main__":
    script_directory = os.path.dirname(os.path.abspath(__file__))
    os.chdir(script_directory)
    uvicorn.run("main:app", host="localhost", port=8888, reload=True)
